﻿using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Data.OleDb;
using System.Data;
using System.Text.RegularExpressions;

/// <summary>
///GetTags 的摘要说明
/// </summary>
public class GetTags
{
    public GetTags()
    {
    }
    /// <summary>
    /// 获取关键字标签 错误时返回源码
    /// </summary>
    /// <param name="title">标题</param>
    /// <param name="cnn">内容</param>
    /// <returns>获取关键字标签 错误时返回源码</returns>
    public string GetTag(string title, string cnn)
    {
        string key = "";

        cnn = StripHTML(cnn);
        cnn = cnn.Replace("&", "");
        cnn = cnn.Replace("#", "");
        if (cnn.Length > 900)
        {
            cnn = cnn.Substring(0, 899);
        }
        string url = "http://keyword.discuz.com/related_kw.html?title=" + title + "&content=" + cnn + "&ics=utf-8";
        string conn = Getsite(url);
        if (conn.IndexOf("]]></kw>") > -1)
        {
            string[] KeyList = StringSplit(conn, "]]></kw>");
            foreach (string a in KeyList)
            {

                //a.Substring(a.LastIndexOf("["))+"<br/>"
                if (a.LastIndexOf("[") > -1)
                {
                    key += a.Substring(a.LastIndexOf("[") + 1) + ",";
                }
            }
            key = key.Substring(0, key.Length - 1);
        }
        else
        {
            key = conn;
        }
        return key;

    }
    private string Getsite(string Url)
    {
        string param = "";
        CookieContainer cc = new CookieContainer();
        byte[] bs = Encoding.ASCII.GetBytes(param);
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(Url);
        req.CookieContainer = cc;
        HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();
        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("gb2312"));
        string content = reader.ReadToEnd();
        reader.Close();
        myResponse.Close();

        return content;
    }
    /// <summary>
    /// 将字符串分割成数组
    /// </summary>
    /// <param name="strSource"></param>
    /// <param name="strSplit"></param>
    /// <returns></returns>
    private string[] StringSplit(string strSource, string strSplit)
    {
        string[] strtmp = new string[1];
        int index = strSource.IndexOf(strSplit, 0);
        if (index < 0)
        {
            strtmp[0] = strSource;
            return strtmp;
        }
        else
        {
            strtmp[0] = strSource.Substring(0, index);
            return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp);
        }
    }
    /// <summary>
    /// 获取相关文章根据关键字 关键字之间用英文,号隔开
    /// </summary>
    /// <param name="keyList"> 关键字 之间用英文,号隔开</param>
    /// <returns>返回相关文章 为空时返回"" </returns>
    public string GetXiangGuanWenZhang(string keyList)
    {
        string str = "<p>相关文章：<br/>";
        Hashtable xg = new Hashtable();
        string[] key = keyList.Split(',');
        for (int s = 0; s < key.Length; s++)
        {
            xg = SelLikeForKey(key[s].ToString(), xg);

        }
        //遍历Hashtable中的键跟值，同时进行关键字替换
        System.Collections.IDictionaryEnumerator enumerator = xg.GetEnumerator();
        int i = 0;
        while (enumerator.MoveNext())
        {
            i++;
            if (i < 9)
            {
                str += "<span style='width: 350px;display: block;float: left;line-height: 28px;'><a href='http://www.fuhepo.cn/" + enumerator.Key.ToString() + "'>" + enumerator.Value.ToString() + "</a></span>";
            }
        }
        if (str == "<p>相关文章：<br/>")
        {
            str = "";
        }
        //str += "</ul>";
        return str;
    }
    /// <summary>
    /// 获取相关文章根据关键字 关键字之间用英文,号隔开
    /// </summary>
    /// <param name="keyList"> 关键字 之间用英文,号隔开</param>
    /// <returns>返回相关文章 为空时返回"" </returns>
    public string GetXiangGuanWenZhang(string keyList, string Nid)
    {
        string str = "<p>相关文章：<br/>";
        Hashtable xg = new Hashtable();
        string[] key = keyList.Split(',');
        for (int s = 0; s < key.Length; s++)
        {
            xg = SelLikeForKey(key[s].ToString(), xg);

        }
        //遍历Hashtable中的键跟值，同时进行关键字替换
        System.Collections.IDictionaryEnumerator enumerator = xg.GetEnumerator();
        int i = 0;
        while (enumerator.MoveNext())
        {
            if (enumerator.Key.ToString() != Nid.ToString())
            {
                i++;
                if (i < 9)
                {
                    str += "<span style='width: 350px;display: block;float: left;line-height: 28px;'><a href='http://www.fuhepo.cn/" + enumerator.Key.ToString() + "'>" + enumerator.Value.ToString() + "</a></span>";
                }
            }
        }
        if (str == "<p>相关文章：<br/>")
        {
            str = "";
        }
        //str += "</ul>";
        return str;
    }
    private Hashtable SelLikeForKey(string key, Hashtable xg)
    {
        OleDbConnection myconn = new OleDbConnection(DB.conn);
        OleDbCommand mycmd = new OleDbCommand("Select Htmlurl,Ntitle from [News] where Nkey LIKE '%" + key + "%' Order BY NID DESC ", myconn);
        OleDbDataReader dr = null;
        try
        {
            myconn.Open();
            dr = mycmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch (OleDbException ex)
        {
            throw new Exception(ex.Message, ex);
        }
        while (dr.Read())
        {
            if (xg[dr["Htmlurl"].ToString()] == null)
            {
                xg.Add(dr["Htmlurl"].ToString(), dr["Ntitle"].ToString());
            }

        }
        dr.Close();
        dr.Dispose();
        return xg;
    }
    /// <summary>
    /// 采用递归将字符串分割成数组
    /// </summary>
    /// <param name="strSource"></param>
    /// <param name="strSplit"></param>
    /// <param name="attachArray"></param>
    /// <returns></returns>
    private string[] StringSplit(string strSource, string strSplit, string[] attachArray)
    {
        string[] strtmp = new string[attachArray.Length + 1];
        attachArray.CopyTo(strtmp, 0);

        int index = strSource.IndexOf(strSplit, 0);
        if (index < 0)
        {
            strtmp[attachArray.Length] = strSource;
            return strtmp;
        }
        else
        {
            strtmp[attachArray.Length] = strSource.Substring(0, index);
            return StringSplit(strSource.Substring(index + strSplit.Length), strSplit, strtmp);
        }
    }
    public static string StripHTML(string strHtml)
    {
        string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""''])(\\[""''tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
@"([\r\n])[\s]+",
@"&(quot|#34);",
@"&(amp|#38);",
@"&(lt|#60);",
@"&(gt|#62);",
@"&(nbsp|#160);",
@"&(iexcl|#161);",
@"&(cent|#162);",
@"&(pound|#163);",
@"&(copy|#169);",
@"&#(\d+);",
@"-->",
@"<!--.*\n"
};
        string[] aryRep = {
"",
"",
"",
"\"",
"&",
"<",
">",
" ",
"\xa1",//chr(161), 
"\xa2",//chr(162), 
"\xa3",//chr(163), 
"\xa9",//chr(169), 
"",
"\r\n",
""
};
        string newReg = aryReg[0];
        string strOutput = strHtml;
        for (int i = 0; i < aryReg.Length; i++)
        {
            Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
            strOutput = regex.Replace(strOutput, aryRep[i]);
        }
        strOutput.Replace("<", "");
        strOutput.Replace(">", "");
        strOutput.Replace("\r\n", "");
        return strOutput;
    }
}